package com.wang.see.controller;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;


@Controller
public class RoBootController {

	private static Logger logger = Logger.getLogger(RoBootController.class);
	
	@Value("${tuling.api.key}")
	private String APIKEY;
	
	@RequestMapping("/toTalk")
	public String toTalk() {
		return "talk";
	}
	
	@ResponseBody
	@RequestMapping("/talk")
	public String talk(@RequestParam("question") String question) throws Exception {
		String INFO = URLEncoder.encode(question, "utf-8");
		String getURL = "http://www.tuling123.com/openapi/api?key=" + APIKEY + "&info=" + INFO;
		URL getUrl = new URL(getURL);
		HttpURLConnection connection = (HttpURLConnection) getUrl.openConnection();
		connection.connect();
		// 取得输入流，并使用Reader读取
		BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
		StringBuffer sb = new StringBuffer();
		String line = "";
		while ((line = reader.readLine()) != null) 
			sb.append(line);
		
		reader.close();
		// 断开连接
		connection.disconnect();
		logger.info(question+"----========-----"+sb);
		return sb.toString();
	}
}
